﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using PropertyManagementSystemAPI.Models;

namespace PropertyManagementSystemAPI.Controllers
{
    /// <summary>
    /// 房产信息管理
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    [Authorize]
    public class HouseInfoController : ControllerBase
    {
        private readonly IFreeSql db;

        public HouseInfoController(IFreeSql _db)
        {
            this.db = _db;
        }

        /// <summary>
        /// 获取房产信息
        /// </summary>
        /// <param name="page">页数</param>
        /// <param name="limit">页条数</param>
        /// <param name="strName">房产名称</param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult getHouseInfo(int page, int limit, int state, string? strName)
        {
            var list = db.Select<Houseinfo, Ownerinfo>()
                 .LeftJoin((a, b) => a.Hid == b.Hid && b.Isdelete == false)
                .Where((a, b) => ((string.IsNullOrEmpty(strName) || a.Hname.Contains(strName))) && ((state == 2) || (a.Hstate == state)) && a.IsDelete == false)

                .Count(out var total) //总记录数量
                .Page(page, limit)
                .ToList((a, b) => new
                {
                    a.Hid,
                    a.Hname,
                    a.Hnumber,
                    a.Htelephone,
                    a.Homeowner,
                    a.Hremark,
                    a.Hstate,
                    a.HSpecifications,
                    a.IsDelete,
                    b.Orealname
                });

            var json = new
            {
                code = 200,
                total = total,
                data = list
            };
            return Ok(json);
        }


        /// <summary>
        /// 绑定房产信息下拉框
        /// </summary>
        /// <returns>返回对应id和房产名称</returns>、
        [HttpGet]
        [Route("getHouseBindSelect")]
        public IActionResult getHouseBindSelect()
        {
            var list = db.Select<Houseinfo>()
                .Where(a => a.IsDelete == false)
                .ToList(a => new 
                { 
                    a.Hid,
                    Hname = a.Hstate == 1 ? a.Hname + "（该房屋已租出）" : a.Hname,
                    a.Hstate
                });


            return Ok(list);
        }
    }
}
